//
//  SWEditorBaseEditToolbar.swift
//  ChildStory
//
//  Created by linhan on 2016/12/5.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit

class SWEditorBaseEditToolbar: SWEditorExpandToolbar,SWImageCropperDelegate
{
    private var _image:UIImage?
    
    private var _cropper:SWImageCropper = SWImageCropper()
    
    private var _change:Bool = false{
        didSet{
            if _change != oldValue
            {
                _confirmBtn.isEnabled = _change
            }
        }
    }
    
    lazy private var _confirmBtn:UIButton = UIButton(type: .custom)
    
    override init(frame: CGRect) {
        super.init(frame: CGRectMake(0, 0, frame.width, 50))
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        print("DEINIT SWEditorPaintBlurToolbar")
    }
    
    override func toolbarDidAppear(_ animated: Bool)
    {
        if let image = image
        {
            DispatchQueue.global(priority: .default).async {
                self._image = image.clone()
            }
            
            let size:CGSize = canvas?.size ?? CGSizeZero
            var insets:UIEdgeInsets
            if size.width > size.height
            {
                let margin:CGFloat = (size.width - size.height) * 0.5
                insets = UIEdgeInsetsMake(0, margin, 0, margin)
            }
            else
            {
                let margin:CGFloat = (size.height - size.width) * 0.5
                insets = UIEdgeInsetsMake(margin, 0, margin, 0)
            }
            _cropper.frame = CGRectMake(0, 0, size.width, size.height)
            _cropper.contentInsets = insets
            _cropper.image = image
            canvas?.pluginCanvas = _cropper
        }
    }
    
    override func toolbarWillDisappear(_ animated: Bool)
    {
        canvas?.pluginCanvas = nil
    }
    
    private func setup()
    {
        _cropper.delegate = self
        
        let cancelBtn:UIButton = UIButton(type: .custom)
        cancelBtn.setImage(UIImage(named:"editor_icon_cancel"), for: .normal)
        cancelBtn.sizeToFit()
        cancelBtn.frame = CGRectMake(10, height - cancelBtn.height - 10, cancelBtn.width, cancelBtn.height)
        cancelBtn.addTarget(self, action: #selector(cancelBtnTapped), for: .touchUpInside)
        addSubview(cancelBtn)
        
        let confirmBtn:UIButton = UIButton(type: .custom)
        confirmBtn.setImage(UIImage(named:"editor_icon_ok"), for: .normal)
        confirmBtn.sizeToFit()
        confirmBtn.frame = CGRectMake(width - confirmBtn.width - 10, height - confirmBtn.height - 10, confirmBtn.width, confirmBtn.height)
        confirmBtn.addTarget(self, action: #selector(confirmBtnTapped(_:)), for: .touchUpInside)
        addSubview(confirmBtn)
        _confirmBtn = confirmBtn
        
        let flipBtn:UIButton = UIButton(type: .custom)
        flipBtn.setImage(UIImage(named:"editor_basicedit_btn_rotation_flip"), for: .normal)
        flipBtn.sizeToTouchEasy()
        flipBtn.center = CGPointMake(0, height - 33)
        flipBtn.addTarget(self, action: #selector(flipBtnTapped), for: .touchUpInside)
        addSubview(flipBtn)
        
        let rotationBtn:UIButton = UIButton(type: .custom)
        rotationBtn.setImage(UIImage(named:"editor_basicedit_btn_rotation_right"), for: .normal)
        rotationBtn.sizeToTouchEasy()
        rotationBtn.center = CGPointMake(0, height - 33)
        rotationBtn.addTarget(self, action: #selector(rotationBtnTapped), for: .touchUpInside)
        addSubview(rotationBtn)
        
        LayoutUtil.distributeHAverageABS([flipBtn, rotationBtn], containerWidth: width)
    }
    
    func imageCropperDidEndDragging(_ cropper:SWImageCropper)
    {
        _change = true
    }
    
    func imageCropperDidEndZooming(_ cropper:SWImageCropper)
    {
        _change = true
    }
    
    @objc private func flipBtnTapped()
    {
        _change = true
        if let image = _image
        {
            let aImage = ImageUtil.flipHorizontal(image)
            _cropper.image = aImage
            _image = aImage
        }
    }
    
    @objc private func rotationBtnTapped()
    {
        _change = true
        if let image = _image
        {
            let aImage = ImageUtil.rotate(image, angle: 90)
            _cropper.image = aImage
            _image = aImage
        }
    }
    
    @objc private func confirmBtnTapped(_ button:UIButton)
    {
        let cropRectPercent = _cropper.cropRectPercent
        if let image = _image, !cropRectPercent.isEmpty && _change
        {
            let Size:CGSize = image.size
            let cropRect:CGRect = CGRectMake(Size.width * cropRectPercent.x, Size.height * cropRectPercent.y, Size.width * cropRectPercent.width, Size.height * cropRectPercent.height)
            
            SVProgressHUD.show(withStatus: "保存中...")
            button.isEnabled = false
            DispatchQueue.global(priority: .default).async{
                let processedImage = Toucan.Util.croppedImageWithRect(image, rect: cropRect)
                print("croppedImageWithRect:", image.scale, image.size, processedImage.scale, processedImage.size)
                DispatchQueue.main.async{
                    button.isEnabled = true
                    SVProgressHUD.dismiss()
                    self.delegate?.expandToolbarConfirmed(processedImage)
                }//end main_queue
                
                
            }//end global_queue
        }
    }
    
    @objc private func cancelBtnTapped()
    {
        if _change
        {
            canvas?.image = image
        }
        delegate?.expandToolbarCancel()
    }
    
}


